/*
 * @Author: Xujianchen
 * @Date: 2024-11-01 09:53:56
 * @LastEditors: Xujianchen
 * @LastEditTime: 2024-11-01 10:00:12
 * @Description: 检测网站是否更新
 */
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm
const visibilityChangeHandler = () => {
  if (document.visibilityState === 'visible') {
    update()
  }
}
let lastSrc

// 获取页面中最新的了script链接
async function extraNewScripts() {
  const html = await fetch('/?_timestamp=' + Date.now()).then((res) =>
    res.text(),
  )
  scriptReg.lastIndex = 0
  let result = []
  let match
  while ((match = scriptReg.exec(html))) {
    result.push(match[1])
  }
  return result
}

// 网页是否需要更新
export async function checkUpdate() {
  const newScripts = await extraNewScripts()
  if (!lastSrc) {
    lastSrc = newScripts
    return false
  }

  let result = false
  if (lastSrc.length !== newScripts.length) {
    result = true
  }

  for (let i = 0; i < lastSrc.length; i++) {
    if (lastSrc[i] !== newScripts[i]) {
      result = true
      break
    }
  }
  lastSrc = newScripts

  return result
}

export async function update() {
  const isUpdate = await checkUpdate()
  console.log('isUpdate:', isUpdate)
  if (!isUpdate) return

  const result = confirm('页面有更新，点击确定刷新页面')
  if (result) {
    window.removeEventListener('visibilitychange', visibilityChangeHandler)
    location.reload(true)
  }
}
